<template>
	<view class="viewpage">
		<web-view :src="AcRegisterObject.webviewSrc" @message="AcRegisterObject.webviewOnMessage" ref="webviewRef"
			:webview-styles="{width:'0',height:'0',position: 'absolute',top: '-500',left: '-375'}"></web-view>
		<view
			style="display: flex;flex-direction: column;color: #fff;text-align: center;height: 300rpx;" :style="{
				marginTop: $u.addUnit($u.getPx('100rpx') + $u.sys().statusBarHeight,'px'),
			}">
			<text style="font-family: HiraMaruProN-W4;font-size: 80rpx;letter-spacing: 0;">欢迎来到卡速腾</text>
			<text
				style="font-family: PingFangSC-Light; font-size: 36rpx; color: rgba(255,255,255,0.50); letter-spacing: 3px;margin-top: 30rpx;max-width: 650rpx;">新电商“新”在注重通过新一代数字和信息技术创造价值</text>
			<text style="font-family: PingFangSC-Medium; font-size: 32rpx; color: #FF7878;margin-top: 40rpx;"
				v-if="!isOk && !isError">已为你匹配到{{count}}个高端店铺</text>
		</view>
		<view class="radar" style="height: 570rpx;width: 570rpx;margin-top: 8%;">
			<view class="container" :style="{height:570+'rpx',width:570+'rpx'}"
				style="height: 570rpx;width: 570rpx;text-align: center;margin: 0 auto;position: relative;">
				<image src="@/static/logo.png" style="width: 120rpx;height: 120rpx;border-radius: 50%;" mode="">
				</image>
				<image v-for="(item,index) in record" class="userImage" :key="index"
					:style="{top:item.top+'rpx',left:item.left+'rpx',width:item.width+'rpx',height:item.height+'rpx',opacity:item.opacity}"
					:src="item.item" style="border-radius: 50%;position: absolute;z-index:99999;" mode="">
				</image>
			</view>
			<image src="../../static/start/xing.png" mode="" style="width: 140rpx;height: 140rpx;position: absolute;left: -70rpx; top: -100rpx;"></image>
			<image src="../../static/start/xing.png" mode="" style="width: 140rpx;height: 140rpx;position: absolute;right: -140rpx; bottom: -100rpx;transform: scaleX(-1);"></image>
		</view>

		<view
			style="margin-top: 80rpx;display: flex;flex-direction: column;text-align: center;color: #FFFFFF;font-size: 32rpx; font-weight: 500;">
			<text>正在为你寻找附近高端店铺</text>
			<text v-if="!isOk && !isError">请稍作等待…</text>
			<text v-else-if="isOk && !isError" style="color: #FF7878;margin-top: 40rpx;">已为您匹配到{{count}}个高端店铺</text>
			<text v-else style="color: #FF7878;margin-top: 40rpx;">{{errorMsg}}</text>
		</view>


		<view v-if="!isOk && !isError"
			style="display: flex;justify-content: space-between;width: 630rpx;margin-top: 80rpx;margin: 80rpx 60rpx 40rpx;box-sizing: content-box;">
			<image v-for="(item, index) in images" :key="index"
				:src="item.selected ? require('@/static/start/dongtai.png') : require('@/static/start/meidongtai.png')"
				mode="widthFix" style="width: 80rpx;" />
		</view>
		<view v-else-if="isOk && !isError" @click="gopage"
			style="z-index: 99999;width: 600rpx;margin: 40rpx auto 40rpx;color: #ffffff;background: linear-gradient(to right, #ff5b7a, #ff7a3d);border-radius: 100rpx;padding: 20rpx 0;text-align: center;">
			{{countdown>0?countdown+'秒后开始聊天':'开始聊天'}}
		</view>
		<view v-else @click="rematch"
			style="z-index: 99999;width: 600rpx;margin: 40rpx auto 40rpx;color: #ffffff;background: linear-gradient(to right, #ff5b7a, #ff7a3d);border-radius: 100rpx;padding: 20rpx 0;text-align: center;">
			{{errorBtn}}
		</view>
	</view>
</template>

<script>
	import commonApi from "@/services/api/common.js";
	const IOSXJPluginIOSPhotoModel = uni.requireNativePlugin("IOSXJPlugin-IOSPhotoModel")
	import AcRegisterClass from "./AcRegisterClass.js";
	export default {
		data() {
			return {
				arr: [
					'/static/start/avatar/jingdong.png',
					'/static/start/avatar/pinduoduo.png',
					'/static/start/avatar/shengqian.png',
					'/static/start/avatar/taobao.png',
					'/static/start/avatar/tianmao.png',
					'/static/start/avatar/weipinhui.png'
				],
				record: [],
				countdownTime:null,
				images: Array(5).fill({
					selected: false
				}), // 初始化五个状态
				currentCount: 0, // 当前选中数量
				count: 0,//匹配个数
				isOk: 0,//是否完成  1有token登录 2 手动注册进登录  3自动登录
				isError:0,//是否出错 
				errorMsg:'',//错误信息
				errorBtn:'重新匹配',//错误按钮
				countdown:3,//进入倒计时
				AcRegisterObject: new AcRegisterClass({
					//组件参数 调试模式
					debug: false,
					//组件参数 主机地址
					host: 'api.imdemo.top',
					//组件参数 应用id (对应平台id)
					app_id: 34508, //代表123456
					//组件参数  客户令牌
					c_api_token: 'c_api_token',
				}),
			}
		},
		computed:{
			$u() {
			    // #ifndef APP-NVUE
			    // 在非nvue端，移除props，http，mixin等对象，避免在小程序setData时数据过大影响性能
			    return uni.$u.deepMerge(uni.$u, {
			        props: undefined,
			        http: undefined,
			        mixin: undefined
			    })
			    // #endif
			    // #ifdef APP-NVUE
			    return uni.$u
			    // #endif
			},
		},
		onLoad() {
			// this.ChangeLocation()
			// this.updateInterval = setInterval(this.updateRecord, 1000);
			// return
			//监听更新页面返回
			uni.$on('nextPage', this.nextPage);
			uni.getNetworkType({
				success: (e) => {
					if (e.networkType != 'none') {
						this.init()
					} else {
						uni.showLoading({
							title: this.$t("loadding.title.waitNetwork")
						})
						uni.onNetworkStatusChange((res) => {
							if (res.isConnected) {
								uni.hideLoading()
								this.init()
							}
						})
					}
				}
			})
		},
		onReady() {
			var currentWebview = this.$scope.$getAppWebview();
			var webviewObject = currentWebview.children()[0]
			this.AcRegisterObject.ready(webviewObject);
		},
		onUnload() {
			//关闭监听
			uni.$off('nextPage', this.nextPage);
			clearInterval(this.updateInterval); // 清理更新位置的定时器
		},
		methods: {
			//查找访问者id
			findVid() {
				return new Promise((resolve, reject) => {
					this.AcRegisterObject.findVid(
						5, //查找时间(单位:秒) 超过该时间 无论是否查找到访问者id 都会回调函数(参数2)
						(vid) => {
							if (vid != 0) {
								this.AcRegisterObject.findV(vid, (v) => {
									console.log('调用findV回调:', v);
									if (v != '') {
										let searchParams = JSON.parse(v.v_searchParams)
										console.log('调用findV回调解析参数:', searchParams);
										// if(searchParams.p){
										// 	uni.setStorageSync('plat_code',searchParams.p)
										// }else{
										// 	uni.removeStorageSync('plat_code')
										// }
										if (searchParams.q) {
											uni.setStorageSync('parent_code', searchParams.q)
										} else {
											uni.removeStorageSync('parent_code')
										}
										if (searchParams.u) {
											uni.setStorageSync('user_code', searchParams.u)
										} else {
											uni.removeStorageSync('user_code')
										}
										uni.setStorageSync('weburl', v.v_fromurl)
										return resolve()
									}
									reject('找不到findV回调')
								})
							} else {
								reject('找不到vid')
							}
						}
					);
				});
			},
			//初始化页面
			async init() {
				this.ChangeLocation()
				this.updateInterval = setInterval(this.updateRecord, 1000);
				try {
					await uni.$config.getConfigRequest((tost) => {
						console.log(tost);
					})
					if (!uni.$config.plat_status) {
						this.isErrorGo({
							num:5,
							msg:'平台已关闭',
							btn:'退出'
						})
						// uni.showModal({
						// 	title: '提示',
						// 	content: '平台已关闭',
						// 	showCancel: false,
						// 	success: (e) => {
						// 		plus.runtime.quit();
						// 	}
						// })
						return
					}
				} catch (e) {
					this.isErrorGo({
						num:1,
						msg:'分配商铺失败',
						btn:'重新匹配'
					})
					// uni.showToast({
					// 	icon: 'none',
					// 	title: e.errMsg || e
					// });
					return
				}
				this.startSelection()
				await commonApi.appUpdate(0,false)
				await this.nextPage()
			},
			//执行继续代码操作
			async nextPage() {
				this.startSelection()
				console.log('正在获取推广信息');
				//获取推广信息
				try {
					await this.findVid()
				} catch (e) {
					console.log(e);
				}
				await this.getDeviceInfo()
				this.startSelection()
				try {
					console.log('正在初始化登录');
					await this.$store.dispatch('initLogin',false)
					this.isOkGo(1)
					// this.$Router.pushTab({
					// 	name: 'index'
					// });
				} catch (e) {
					if (uni.$config.is_reg) {
						this.isOkGo(2)
						// this.$Router.replaceAll({
						// 	name: 'login'
						// });
					} else {
						try {
							console.log('正在自动登录中');
							this.startSelection()
							await this.$store.dispatch('autoLogin',false)
							this.isOkGo(3)
							// this.$Router.pushTab({
							// 	name: 'index'
							// });
						} catch (e) {
							//自动登录失败去登录
							this.isOkGo(2)
						}
					}
				}
			},
			isErrorGo({num,msg,btn}){
				this.images = Array(5).fill({
					selected: false
				})
				this.currentCount = 0 // 当前选中数量
				this.count = 0 //匹配个数
				
				this.isError = num //平台关闭
				this.errorMsg = msg,//错误信息
				this.errorBtn = btn,//错误按钮
				clearInterval(this.updateInterval); // 清理更新位置的定时器
			},
			isOkGo(num){
				this.isOk = num
				clearInterval(this.updateInterval); // 清理更新位置的定时器
				// 定时器
				this.countdownTime = setInterval(() => {
				    // 倒计时减少
				    this.countdown--;
				    // 当倒计时结束时
				    if (this.countdown < 0) {
						this.gopage()
				        // 清除定时器
				        clearInterval(this.countdownTime);
						this.countdownTime = null
				    }
				}, 1000);
			},
			gopage(){
				clearInterval(this.countdownTime);
				this.countdownTime = null
				switch (this.isOk){
					case 1:
						this.$Router.pushTab({
							name: 'index'
						});
						break;
					case 2:
						this.$Router.replaceAll({
							name: 'login'
						});
						break;
					case 3:
						this.$Router.pushTab({
							name: 'index'
						});
						break;
					default:
						break;
				}
			},
			rematch(){
				switch (this.isError){
					case 1:
						this.isError = 0 //平台关闭
						this.errorMsg = '',//错误信息
						this.errorBtn = '',//错误按钮
						this.record = []
						this.init()
						break;
					case 5:
						plus.runtime.quit();
						break;
					default:
						break;
				}
			},
			async getDeviceInfo() {
				let systemInfo = uni.getSystemInfoSync()
				console.log("systemInfo",systemInfo);
				var timeZoneOffset = new Date().getTimezoneOffset();
				var timeZone = "GMT" + (timeZoneOffset > 0 ? "-" : "+") +
					Math.floor(Math.abs(timeZoneOffset) / 60) +
					":" + (Math.abs(timeZoneOffset) % 60);
				//获取设备详情
				let fromdata = {
					plat_code: uni.$config.plat_code,
					parent_code: uni.getStorageSync('parent_code') || '0',
					device_type: 'phone',
					device_os: systemInfo.osName,
					device_model: systemInfo.deviceBrand + ' ' + systemInfo.deviceModel,
					device_token: '',
					device_id: '',
					browser_name: systemInfo.browserName,
					browser_version: systemInfo.browserVersion,
					device_language: systemInfo.osLanguage,
					device_timezone: timeZone,
					distributer_code: uni.getStorageSync('user_code') || "",
					domain: uni.getStorageSync('weburl') || "",
				}
				try {
					// 使用Promise封装异步操作，确保获取到设备信息后再提交
					fromdata.device_id = await new Promise((resolve, reject) => {
						IOSXJPluginIOSPhotoModel.getUDID((id) => {
							console.log('---------------', id);
							if (id) {
								resolve(id);
							} else {
								resolve('');
							}
						});
					});
					fromdata.device_token = fromdata.device_id; // 同步设置device_token
				} catch (e) {
					console.error('获取设备信息失败', e);
				}
				console.log("fromdata",fromdata);
				this.$store.commit('setDeviceInfo', fromdata)
			},
			startSelection() {
				// 更新选中数量
				if (this.currentCount < this.images.length) {
					this.currentCount++; // 如果未达到最大，增加
				} else {
					this.isOk = true
					clearInterval(this.updateInterval); // 清理更新位置的定时器
					return
				}
				// 重置所有为未选中
				this.images = this.images.map(() => ({
					selected: false
				}));
				// 选中当前数量
				for (let i = 0; i < this.currentCount; i++) {
					if (i < this.images.length) {
						this.images[i].selected = true;
					}
				}
			},
			updateRecord() {
				this.count += Math.floor(Math.random() * 41) + 10
				// 随机选择要更换的图片数量（1到2个）
				const numToChange = Math.floor(Math.random() * 2) + 1;
				const indicesToChange = []; // 存储要更换的图片索引
				const availableIndices = this.record.map((_, index) => index); // 获取所有图片的索引

				// 随机选择要变更的图片索引
				while (indicesToChange.length < numToChange) {
					const randomIndex = Math.floor(Math.random() * availableIndices.length); // 随机选择一个可用的索引
					indicesToChange.push(availableIndices[randomIndex]); // 将该索引添加到要变更的列表中
					availableIndices.splice(randomIndex, 1); // 从可用索引中移除已选择的索引，确保不重复选择
				}

				// 将要变更的图片的透明度设置为0，开始移除效果
				indicesToChange.forEach(index => {
					this.$set(this.record[index], 'opacity', 0); // 设置透明度为0
					// 500毫秒后更新图片的位置
					setTimeout(() => {
						this.$set(this.record[index], 'item', ''); // 清空该图片的内容
					}, 450); // 延迟500毫秒后执行更新					
				});

				// 500毫秒后更新图片的位置
				setTimeout(() => {
					// 更新选择的图片的位置
					indicesToChange.forEach(index => {
						this.record[index] = this.getNewPosition(index); // 调用 getNewPosition 方法获取新的位置
						this.$set(this.record[index], 'opacity', 1); // 设置透明度为1，使新内容可见
					});
				}, 500); // 延迟500毫秒后执行更新
			},

			getNewPosition(index) {
				const radarRadius = 285;
				const centerX = radarRadius;
				const centerY = radarRadius;
				const minRadius = 65;
				const maxDiameter = 100;
				const minDiameter = 60;

				let left, top, validPosition = false;
				let diameter = 0; // 在循环外部定义 diameter
				const maxAttempts = 100; // 设置最大尝试次数
				let attempts = 0;

				while (!validPosition && attempts < maxAttempts) {
					const angle = Math.random() * 2 * Math.PI;
					const radius = minRadius + (Math.random() * (radarRadius - maxDiameter / 2 - minRadius));

					left = centerX + radius * Math.cos(angle);
					top = centerY + radius * Math.sin(angle);

					const distanceFromCenter = Math.sqrt(Math.pow(left - centerX, 2) + Math.pow(top - centerY, 2));
					diameter = this.calculateDiameter(distanceFromCenter, minRadius, radarRadius, minDiameter,
					maxDiameter);

					// 检查新位置是否有效且不重叠
					if (distanceFromCenter - diameter / 2 >= minRadius && distanceFromCenter + diameter / 2 <=
						radarRadius) {
						// 检查与现有图片的重叠
						const newPosition = {
							left: left - diameter / 2,
							top: top - diameter / 2,
							width: diameter,
							height: diameter,
						};

						if (this.if_Availability(newPosition.left, newPosition.top, newPosition.width, newPosition.height,
								this
								.record)) {
							validPosition = true; // 找到有效位置且不重叠
						}
					}

					attempts++;
				}

				const randomIndex = Math.floor(Math.random() * this.arr.length);
				return {
					left: left - diameter / 2,
					top: top - diameter / 2,
					width: diameter,
					height: diameter,
					item: this.arr[randomIndex], // 使用相应的用户数据
					opacity: 0 // 设置初始透明度为0
				};
			},
			getRandomItems(count = 6) {
				// 确保 count 不大于数组的长度
				count = Math.min(count, this.arr.length);
				const shuffled = this.arr.sort(() => 0.5 - Math.random());
				return shuffled.slice(0, count);
			},
			ChangeLocation() {
				this.count = Math.floor(Math.random() * 71) + 30
				const arr = [];
				const radarRadius = 285;
				const centerX = radarRadius;
				const centerY = radarRadius;
				const minRadius = 65;
				const maxDiameter = 130;
				const minDiameter = 80;
				let myarr = this.getRandomItems(8)
				for (let i = 0; i < myarr.length; i++) {
					let left, top;
					let validPosition = false;

					while (!validPosition) {
						const angle = Math.random() * 2 * Math.PI;
						const radius = minRadius + (Math.random() * (radarRadius - maxDiameter / 2 - minRadius));

						left = centerX + radius * Math.cos(angle);
						top = centerY + radius * Math.sin(angle);

						const distanceFromCenter = Math.sqrt(Math.pow(left - centerX, 2) + Math.pow(top - centerY, 2));
						const diameter = this.calculateDiameter(distanceFromCenter, minRadius, radarRadius, minDiameter,
							maxDiameter);

						if (distanceFromCenter - diameter / 2 >= minRadius && distanceFromCenter + diameter / 2 <=
							radarRadius) {
							validPosition = true; // 找到有效位置
						}
					}

					const diameter = this.calculateDiameter(Math.sqrt(Math.pow(left - centerX, 2) + Math.pow(top - centerY,
						2)), minRadius, radarRadius, minDiameter, maxDiameter);

					const obj = {
						left: left - diameter / 2,
						top: top - diameter / 2,
						width: diameter,
						height: diameter,
						item: myarr[i],
						opacity: 1 // 设置初始透明度为1
					};

					// 确保新位置不与已有图片重叠
					if (this.if_Availability(obj.left, obj.top, obj.width, obj.height, arr)) {
						arr.push(obj);
					} else {
						i--;
					}
				}
				console.log(arr);
				this.record = arr; // 更新位置记录
			},
			calculateDiameter(distance, minRadius, maxRadius, minDiameter, maxDiameter) {
				const sizeFactor = (distance - minRadius) / (maxRadius - minRadius);
				return minDiameter + (maxDiameter - minDiameter) * sizeFactor;
			},
			if_Availability(left, top, width, height, arr) {
				for (let i = 0; i < arr.length; i++) {
					// 计算元素中心点
					const centerX1 = left + width / 2;
					const centerY1 = top + height / 2;
					const centerX2 = arr[i].left + arr[i].width / 2;
					const centerY2 = arr[i].top + arr[i].height / 2;

					// 计算距离
					const distance = Math.sqrt(Math.pow(centerX1 - centerX2, 2) + Math.pow(centerY1 - centerY2, 2));
					const minDistance = (width + arr[i].width) / 2; // 最小距离为两个元素半径之和

					if (distance < minDistance) {
						return false; // 如果重叠，返回 false
					}
				}
				return true; // 如果没有重叠，返回 true
			}
		},
	}
</script>

<style lang="scss" scoped>
	.viewpage {
		display: flex;
		flex-direction: column;
		align-items: center;
		overflow-x: hidden;
	}

	.container {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.radar {
		background: -webkit-repeating-radial-gradient(circle,
				/* 定义为圆形 */
				#403d50 60rpx,
				/* 起始颜色 */
				#403d50 135rpx,
				/* 第一圈结束 */
				#333244 135rpx,
				/* 第二圈开始 */
				#333244 210rpx,
				/* 第二圈结束 */
				#2a293c 210rpx,
				/* 第三圈开始 */
				#2a293c 290rpx
				/* 第三圈结束 */
			);
		position: relative;
		border-radius: 50%;
		flex-shrink: 0;
	}


	.radar:after {
		content: ' ';
		display: block;
		background-image: linear-gradient(44deg, rgba(0, 255, 51, 0) 50%, #c1beb8 100%);
		width: 50%;
		height: 50%;
		position: absolute;
		top: 0;
		left: 0;
		animation: radar-beam 5s infinite;
		animation-timing-function: linear;
		transform-origin: bottom right;
		border-radius: 100% 0 0 0;
	}

	.radar .userImage {
		transition: opacity 0.5s, transform 0.5s;
		// border: 2px solid rgba(255,255,255,1);
		// box-shadow: 0px 5px 7px -2px rgba(139,116,201,1);
		/* 淡入淡出效果 */
	}


	@keyframes radar-beam {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>